//
//  YMSStatusesViewModel.swift
//  YMSWeibo
//
//  Created by 杨茂盛 on 2016/11/16.
//  Copyright © 2016年 杨茂盛. All rights reserved.
//
//  微博cell的视图模型,用来处理微博cell显示的数据

import UIKit

class YMSStatusesViewModel: NSObject {

    var iconUrl:URL?//头像图片地址
    var verifitedImage :UIImage? //用户认证
    var mbRankImage:UIImage?//用户等级
    //来源
    var sourceText :String?
    //设置行高 只希望计算一次 以后就直接读取
    var rowHeight: CGFloat = 300

    //原创微博的属性字符串
    var originalAttributedString:NSMutableAttributedString?
    //转发微博的属性字符串
    var retweetedAttributedString:NSMutableAttributedString?
    
    
    
    //时间
    var timeText :String {
    
        //实例化日期格式化对象
        let dateFormate = DateFormatter()
        //指定格式化符
        dateFormate.dateFormat = "EEE MMM dd HH:mm:ss Z yyy"
        //在真机上必须设置本地信息否则转化失败
        dateFormate.locale = Locale(identifier: "en")
        //将字符串转成日期对象
        guard let sinaDate = dateFormate.date(from: status?.created_at ?? "")else{
            return "你特么哪里人"
        }
        //print(sinaDate)
        //处理日期
        //判断是否是今年
        let calender = Calendar.current
        let currentDate = Date()
        let result = calender.dateComponents([.day,.year], from: sinaDate, to: currentDate)
        
        if result.year == 0 {
            //今年
            if calender.isDateInToday(sinaDate) {
                //今天
                //获取当前的时间和sinDate秒的差距
                let delta = currentDate.timeIntervalSince(sinaDate)
                if delta < 60 {
                    //说明小于一分钟,是刚刚发的
                    return "刚刚"
                }else if delta < 3600{
                    return  "\(Int(delta / 60))分钟前"
                }else{
                    return "\(Int(delta / 3600))小时前"
                }
            }else if calender.isDateInYesterday(sinaDate){
                //昨天 HH:mm
                dateFormate.dateFormat = "昨天 HH:mm"
                return dateFormate.string(from: sinaDate)
            }else{
                //其它 MM-dd HH:mm
                dateFormate.dateFormat = "MM-dd HH:mm"
                return dateFormate.string(from: sinaDate)
            }
        }else{
            //不是今年
            dateFormate.dateFormat = "yyyy-MM-dd HH:mm"
            return dateFormate.string(from: sinaDate)
        }

    }
    
    //计算型的属性,判断要返回什么类型微博的pic_urls
    var imageUrls:[YMSPicture]?{
        //判断是否转发
            if status?.retweeted_status == nil {
                //要显示原创微博
                return status?.pic_urls
            }
            //转发微博
            return status?.retweeted_status?.pic_urls
    }
    
    //处理数据相关的业务逻辑 处理微博日期,微博来源
    var status:YMSStatuses?{
        didSet{
            iconUrl = URL(string: status?.user?.avatar_large ?? "")
            //处理微博认证的信息
            self.dealMbrankImage()
            self.dealWeiboVerifiedImage()
            //'self.timeText = dealWeiboDate(str: status?.created_at ?? "")
            self.sourceText = dealWeiboSource(source: status?.source ?? "")
            
            //微博原创和转发的文本内容
            self.originalAttributedString = self.dealWeiboText(str: status?.text ?? "")
            self.retweetedAttributedString = self.dealWeiboText(str: status?.retweeted_status?.text ?? "")
            
        }
    }
    
//--------------------------将微博正文/转发微博正文处理成富文本------------------------------------
    
    private func dealWeiboText(str:String)-> NSMutableAttributedString{
        // [.*?]  在正则表达式中表示一位 需要转义 //要查找的东西
        let pattern = "\\[.*?\\]"
        
        //1.实例化正则表达式 设置查找规则
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        //2.通过规则在字符串中查找目标字符串 -> NSTextcheckResult
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
        
        //3、将str转换为可变的富文本
        let strM = NSMutableAttributedString(string: str)
        let font = UIFont.systemFont(ofSize: 15)
        let lineHeight = font.lineHeight
        
        //4.遍历结果集 获取表情字符串 ->倒序遍历
        for result in results.reversed() { //MARK:这里为什么要倒序?如果正序的话,当前位置的图片会影响后面的大小(当前位置的字符大小会以前面的为标准,所以要倒序,倒序不会影响前面的)
            let range = result.rangeAt(0)
            let sub = (str as NSString).substring(with: range)
            
            //4.根据表情字符串在表情数组中查找对应的表情模型(图片路径)
            if let em = HMEmoticonTools.sharedEmoticonTools.findEmoticon(chs: sub){

                print(em)
                //5.将图片转换成富文本 必须要使用YYText提供的富文本的实例方法
                let image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
                let imageText = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit, attachmentSize: CGSize(width:lineHeight,height:lineHeight), alignTo: font, alignment: .center)
                
                //6.将图片富文本替换到str对应的可变富文本中
                strM.replaceCharacters(in: range, with: imageText)
                
            }
        }
        //7.给富文本添加字体的属性
        strM.addAttributes([NSFontAttributeName:font], range: NSRange(location: 0, length: strM.length))
        //某人
        addHiglighttedText(pattern: "@\\w+", strM: strM)
        //某频道
        addHiglighttedText(pattern: "#.*?#", strM: strM)
        //网址
        addHiglighttedText(pattern: "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?", strM: strM)
        
        return strM
    }
//--------------------------特殊文本的处理(颜色,大小,高亮)-----------------------------
    private func addHiglighttedText(pattern:String,strM:NSMutableAttributedString){
        
        //@某人
        
        //1.实例化正则表达式 设置查找规则
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        let str = strM.string
        
        //2.通过规则在字符串中查找到目标字符串 NSTextcheckResult
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
        //3.遍历循环
        for result in results {
            
            let range = result.rangeAt(0)
            //给目标字符串添加颜色
            strM.addAttributes([NSForegroundColorAttributeName:UIColor.orange], range: range)
            
            
            //给特殊的文本添加点击事件
            
            
            //设置高亮时文字的颜色
            let border = YYTextBorder(fill: UIColor.gray, cornerRadius: 3)
            let highlight = YYTextHighlight()
            
            highlight.setColor(UIColor.orange)
            highlight.setBackgroundBorder(border)
            //把高亮属性应用设置到某个文本范围
            strM.yy_setTextHighlight(highlight, range: range)
        }
    }
 
    
    //--------------------------处理微博来源------------------------------------
    func dealWeiboSource(source:String) -> String{
        //<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">iPhone 6s 土豪金</a>
        
        let startFlag = "\">"
        let endFlag = "</a>"
        
        guard let startRange = source.range(of: startFlag),let endRange = source.range(of: endFlag) else {
            return "来自火星"
        }
        
        //upperBound 最大边界  lowerBound 最小边界
        let range = startRange.upperBound..<endRange.lowerBound
        let subStr = source.substring(with: range)
        return subStr
    }
    
//--------------------------处理事件------------------------------------
    //处理用户等级的照片
    private func dealMbrankImage(){
        let mbrank = status?.user?.mbrank ?? 0
        if mbrank > 0 && mbrank < 7 {
            //赋值
            mbRankImage = UIImage(named: "common_icon_membership_level\(mbrank)")
        }
    }

    //处理微博相关的业务逻辑 处理微博日期 微博来源
    private func dealWeiboVerifiedImage(){
        //微博认证的图片
        let type = status?.user?.verified_type ?? -1
        //判断type
        switch type {
        case 0:
            verifitedImage = #imageLiteral(resourceName: "avatar_vip")
        case 2,3,5:
            verifitedImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
        case 220:
            verifitedImage = #imageLiteral(resourceName: "avatar_grassroot")
        default:
            verifitedImage = nil
        }
    }
}
